package handler;

import enums.MessageType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import protocol.Header;
import protocol.NettyMessage;

/**
 * 客户端登录
 */
public class LoginAuthReqHandler extends ChannelInboundHandlerAdapter {

    /**
     * 建立连接时调用
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(buildLoginReq());
        System.out.println("client 发起登录"+System.currentTimeMillis());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("登录请求响应");
        NettyMessage message = (NettyMessage) msg;
        //如果是握手应答消息,需要判断是否认证成功
        if(message.getHeader() != null
            && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
            //这里还需要验证是否握手成功,如果失败关闭链接
            byte longinResult = 0;//(byte) message.getBody();
            if (longinResult != 0) {
                ctx.close();
            } else{
                System.out.println("login is ok : " + message);
                ctx.fireChannelRead(msg);
            }
        }else {
            ctx.fireChannelRead(msg);
        }
    }
    public NettyMessage buildLoginReq(){
        NettyMessage message = new NettyMessage();
        Header header = new Header();
        header.setType(MessageType.LOGIN_REQ.value());
        message.setHeader(header);
        //message.setBody((byte)0);
        return message;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
